<template>
  <div>
    <!--  面包屑导航 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片  -->
    <el-card>
      <!--  警告提示  -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false" show-icon type="warning"></el-alert>
      <!--  级联选择器选择商品分类  -->
      <el-row class="mt">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader v-model="selectedId" :options="cateList" clearable
                       :props="{  label:'cat_name' ,value:'cat_id', children:'children' ,expandTrigger: 'hover' }"
                       @change="selectChange"></el-cascader>
        </el-col>
      </el-row>
      <!--  tabs标签页渲染分类参数 -->
      <el-tabs v-model="activeName" @tab-click="selectTab">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="addDialogVisible = true" :disabled="isDisabled" size="mini">添加参数</el-button>
          <!--  动态参数列表  -->
          <el-table :data="manyList" border stripe>
            <el-table-column type="expand">
              <!-- 在展开项中 作用域插槽形式接收数据 -->
              <template slot-scope="scope">
                <el-tag closable @close="closeTag(i,scope.row)" :key="i" v-for="(item,i) in scope.row.attr_vals">
                  {{item}}
                </el-tag>
                <el-input v-model="scope.row.inputValue" class="input-new-tag" @blur="handleInputConfirm(scope.row)"
                          @keyup.enter.native="handleInputConfirm(scope.row)" v-if="scope.row.inputVisible"
                          ref="saveTagInput" size="small"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="alterParams(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteParams(scope.row.attr_id)" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button type="primary" @click="addDialogVisible = true" :disabled="isDisabled" size="mini">添加属性</el-button>
          <!--  静态参数列表  -->
          <el-table :data="onlyList" border stripe>
            <el-table-column type="expand">
              <!-- 在展开项中 作用域插槽形式接收数据 -->
              <template slot-scope="scope">
                <el-tag closable @close="closeTag(i,scope.row)" :key="i" v-for="(item,i) in scope.row.attr_vals">
                  {{item}}
                </el-tag>
                <el-input v-model="scope.row.inputValue" class="input-new-tag" @blur="handleInputConfirm(scope.row)"
                          @keyup.enter.native="handleInputConfirm(scope.row)" v-if="scope.row.inputVisible"
                          ref="saveTagInput" size="small"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="alterParams(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteParams(scope.row.attr_id)" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--  添加参数 和 添加属性的对话框 -->
    <el-dialog @close="addDialogClose" :title="dialogTitle" :visible.sync="addDialogVisible" width="30%">
      <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px">
        <el-form-item :label="labelName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--  编辑对话框 -->
    <el-dialog @close="alterDialogClose" :title="alterDialogTitle" :visible.sync="alterDialogVisible" width="30%">
      <el-form ref="alterFormRef" :rules="alterFormRules" :model="alterForm" label-width="80px">
        <el-form-item :label="labelName" prop="attr_name">
          <el-input v-model="alterForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alterSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        subId: 0,
        alterForm: {},
        alterDialogVisible: false,
        alterFormRules: {
          attr_name: [
            {required: true, message: '该选项不能为空', trigger: 'blur'}
          ]
        },
        addForm: {
          attr_name: ''
        },
        addFormRules: {
          attr_name: [
            {required: true, message: '请输入参数名称', trigger: 'blur'}
          ]
        },
        addDialogVisible: false,
        manyList: [],
        onlyList: [],
        selectEndId: 0,
        activeName: 'many',
        cateList: [],
        selectedId: []
      }
    },
    created() {
      this.getCateList();
    },
    computed: {
      /*  计算商品分类选择的id长度，确定按钮是否禁用 */
      isDisabled() {
        if (this.selectedId.length === 3) {
          return false;
        } else {
          return true;
        }
      },
      /*  动态计算文本  */
      alterDialogTitle() {
        if (this.activeName === 'many') {
          return '修改动态参数';
        } else {
          return '修改静态属性';
        }
      },
      labelName() {
        if (this.activeName === 'many') {
          return '动态参数';
        } else {
          return '静态属性';
        }
      },
      dialogTitle() {
        if (this.activeName === 'many') {
          return '添加动态参数';
        } else {
          return '添加静态属性';
        }
      }
    },

    methods: {
      /*  抽离发起改变tag标签的方法  */
      async putWays(row) {
        const {data: res} = await this.$http.put(`categories/${this.selectEndId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        });
        if (res.meta.status === 200) {
        } else {
          this.$message.error('添加失败');
        }
      },
      /* 监听删除tag标签 */
      async closeTag(index, row) {
        row.attr_vals.splice(index, 1);
        this.putWays(row);
      },
      /*  监听input 失去焦点，或按下 enter 键触发  */
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputVisible = false;
          row.inputValue = '';
          return;
        }
        /*  输入合法，拼接字符串  */
        row.attr_vals.push(row.inputValue.trim());
        row.inputVisible = false;
        row.inputValue = '';
        this.putWays(row);
      },
      /* 点击按钮，显示文本框 */
      showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      /*  删除参数  */
      deleteParams(deleId) {
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: deleteRes} = await this.$http.delete(`categories/${this.selectEndId}/attributes/${deleId}`);
          if (deleteRes.meta.status === 200) {
            this.$message.success("成功删除参数");
            this.getChangeData();
          } else {
            this.$message.error("删除参数失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      /*  确定编辑  */
      alterSubmit() {
        this.$refs.alterFormRef.validate(async (valid) => {
          if (!valid) {
            return;
          } else {
            const {data: subRes} = await this.$http.put(`categories/${this.selectEndId}/attributes/${this.alterForm.attr_id}`, {
                attr_name: this.alterForm.attr_name,
                attr_sel: this.activeName
              }
            );
            if (subRes.meta.status === 200) {
              this.getChangeData();
              this.alterDialogVisible = false;
              this.$message.success('修改成功');
            } else {
              this.$message.error('修改失败');
            }
          }
        })
      },
      /*  监听编辑动态参数  */
      async alterParams(alterData) {
        const {data: alterRes} = await this.$http.get(`categories/${this.selectEndId}/attributes/${alterData.attr_id}`,
          {
            params: {attr_sel: this.activeName}
          });
        if (alterRes.meta.status === 200) {
          this.alterForm = alterRes.data;
          this.alterDialogVisible = true;
        } else {
          this.$message.error('参数请求失败');
        }

      },
      /*  监听修改对话框的关闭 重置对话框  */
      alterDialogClose() {
        this.$refs.alterFormRef.resetFields();
      },
      /*  确定添加参数  */
      addSubmit() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) {
            this.$message.error('error')
          } else {
            const {data: subRes} = await this.$http.post(`categories/${this.selectEndId}/attributes`, {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            });
            if (subRes.meta.status === 201) {
              this.getChangeData();
              this.addDialogVisible = false;
            } else {
              this.$message.error('添加失败');
            }
          }
        })
      },
      /*  监听添加对话框关闭 重置对话框 */
      addDialogClose() {
        this.$refs.addFormRef.resetFields();
      },
      /*  监听tab标签被选中  获取参数列表数据*/
      selectTab() {
        this.getChangeData();
      },
      /*  监听商品分类选择变化 获取参数列表数据  */
      selectChange() {
        if (this.selectedId.length !== 3) {
          this.selectedId = [];
          this.onlyList = [];
          this.manyList = [];
          return;
        } else {
          this.getChangeData();
        }
      },
      /*  获取参数列表数据  */
      async getChangeData() {
        if (this.selectedId.length !== 3) {
          return
        } else {
          this.selectEndId = this.selectedId[this.selectedId.length - 1];
          const {data: chaRes} = await this.$http.get(`categories/${this.selectEndId}/attributes`, {params: {sel: this.activeName}})
          /*  将拿到的字符串的attr_vals 项分割成数组  */
          chaRes.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
            /*  为每一个参数绑定自己的v-model 和 v-for  */
            item.inputValue = '';
            item.inputVisible = false;
          });
          if (chaRes.meta.status === 200) {
            if (this.activeName === 'many') {
              this.manyList = chaRes.data;
            } else {
              this.onlyList = chaRes.data;
            }
          } else {
            this.$message.success('参数列表数据获取失败')
          }
        }
      },
      /*  获取商品分类列表  */
      async getCateList() {
        const {data: res} = await this.$http.get('categories');
        // console.log(res.data);
        if (res.meta.status === 200) {
          this.cateList = res.data;
        } else {
          this.$message.error('获取商品分类数据失败');
        }
      }
    }
  }
</script>

<style scoped>
  .el-cascader {
    width: 30%;
  }

  .el-tabs {
    margin-top: 15px;
  }

  .el-tag {
    margin-right: 15px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
